from PyQt5.QtCore import *
from PyQt5.QtGui import QFocusEvent
from examples.example_calculator.calc_conf import *
#from calc_conf import *#--
from examples.example_calculator.calc_node_base import *
#from calc_node_base import *#--
from nodeeditor.utils import dumpException

import examples.example_calculator.tuoZhan as tuoZhan
_path = tuoZhan.Task_GetPath(0)#当前jiaoben目录

#查找图片，如果找到的话，就点击某个位置
class CalcGraphicsNode(QDMGraphicsNode):#节点外壳
    def initSizes(self):
        super().initSizes()
        self.width = 300
        self.height = 115
        self.edge_roundness = 6
        self.edge_padding = 0
        self.title_horizontal_padding = 8
        self.title_vertical_padding = 10

    def initAssets(self):
        super().initAssets()
        self.icons = QImage("icons/status_icons.png")

    def paint(self, painter, QStyleOptionGraphicsItem, widget=None):
        super().paint(painter, QStyleOptionGraphicsItem, widget)

        offset = 24.0
        if self.node.isDirty(): offset = 0.0
        if self.node.isInvalid(): offset = 48.0

        painter.drawImage(
            QRectF(-10, -10, 24.0, 24.0),
            self.icons,
            QRectF(offset, 0, 24.0, 24.0)
        )


class CalcImageClickContent(QDMNodeContentWidget):
    def initUI(self):
        self.layout = QVBoxLayout()
        self.layout.setContentsMargins(10,0,10,0)
        self.setLayout(self.layout)
        
        self.edit = QTextEdit("#请先截图，然后点击下方按钮", self)
        self.edit.setAlignment(Qt.AlignLeft)
        self.edit.setObjectName(self.node.content_label_objname)
        self.edit.setEnabled(False)#禁用文本框
        
        self.edit2 = QLineEdit("0000", self)#此框输入任务编号
        self.edit2.setAlignment(Qt.AlignLeft)
        
        self.button = QPushButton(text="从剪切板导入",parent=self)
        self.button2 = QPushButton(text="截图",parent=self)
        
        self.h_layout = QHBoxLayout()
        self.h_layout.addWidget(self.button)
        self.h_layout.addWidget(self.edit2)
        self.h_layout.addWidget(self.button2)
        
        self.label = QLabel(self)
        
        self.layout.addWidget(self.edit)
        self.layout.addLayout(self.h_layout)
        self.layout.addWidget(self.label)
        
        self.edit.setMaximumSize(QSize(300,50))
        self.button.setMaximumSize(QSize(300,25))
        self.edit2.setMaximumSize(QSize(40,20))
        
    def openimage(self,name01,name02):
        #imgName, imgType = QFileDialog.getOpenFileName(self, "打开图片", "", "*.bmp")
        imgName = _path + "\\List\\" + name01 + "\\" + name02 + ".bmp"
        print("图**********")
        print(imgName)
        jpg = QPixmap(imgName)
        self.label.width = jpg.width()
        self.label.height = jpg.height()
        self.label.setPixmap(jpg)
    
    def serialize(self):
        res = super().serialize()
        res['value'] = self.edit.toPlainText()#代码
        res['value2'] = self.edit2.text()#任务编号
        return res

    def deserialize(self, data, hashmap={}):
        res = super().deserialize(data, hashmap)
        try:
            value = data['value']
            value2 = data['value2']
            self.edit.setText(value)
            self.edit2.setText(value2)
            return True & res
        except Exception as e:
            dumpException(e)
        return res

@register_node(OP_NODE_IMAGE_CLICK)
class CalcNode_ImageClick(CalcNode):
    icon = "icons/in.png"
    op_code = OP_NODE_IMAGE_CLICK
    op_title = "存在图片就点击某处"
    content_label_objname = "calc_node_image_click"
    GraphicsNode_class = CalcGraphicsNode

    def __init__(self, scene):
        super().__init__(scene, inputs=[], outputs=[1])
        self.eval()
        
        self.time02 = QTimer()
        self.time02.timeout.connect(self.time03)
        self.time02.setInterval(2000)
        self.time02.start()

    def initInnerClasses(self):
        self.content = CalcImageClickContent(self)
        self.grNode = CalcGraphicsNode(self)
        self.content.edit.textChanged.connect(self.onInputChanged)
        self.content.edit2.textChanged.connect(self.onInputChanged)
        self.content.button.clicked.connect(self.getClipboard)
        self.content.button2.clicked.connect(self.jieTu)#截图
    
    def evalImplementation(self):
        s_value = self.content.edit.toPlainText()
        self.value = s_value
        self.markDirty(False)
        self.markInvalid(False)

        self.markDescendantsInvalid(False)
        self.markDescendantsDirty()

        self.grNode.setToolTip("")

        self.evalChildren()

        return self.value

    def getClipboard(self):
        #从剪切板中获取代码
        clipboard = QApplication.clipboard()
        str01 = clipboard.text()
        if(str01.count("Fun") == 2):
            if(str01.count(",0) == 1)") == 1):
                self.content.edit.setText("#操作失败：此节点不具备点击图功能，请尝试点击此图节点")
                return 0
            self.content.edit.setText(clipboard.text())
            
            int01 = str01.find('") == 1):')
            
            self.content.openimage(str01[8:12],str01[15:int01])

            self.grNode.height = 115 + self.content.label.height
            if(self.content.label.width <= 300):
                self.grNode.width = 300
            else:
                self.grNode.width = self.content.label.width
            self.grNode.initContent()
            #self.initSockets(inputs=[], outputs=[1])
            self.time02 = QTimer()
            self.time02.timeout.connect(self.time01)
            self.time02.setInterval(500)
            self.time02.start()
        else:
            self.content.edit.setText("#操作失败：你需要先使用截图工具")
        pass
    
    def jieTu(self):
        #截图
        try:
            tuoZhan.open_ScreenSpy()
            tuoZhan.ScreenSpy(self.content.edit2.text())
        except:
            print("截图失败！请检查路径中有无截图程序")
        pass
    
    def time01(self):
        #print("延迟1秒")
        self.time02.stop()
        self.grNode.initContent()
        #self.initSockets(inputs=[], outputs=[1])
    
    def time03(self):
        #print("延迟1秒")
        self.time02.stop()
        self.startSetImage()#尝试恢复图片
    
    def startSetImage(self):
        #开始时设置图片
        str01 = self.content.edit.toPlainText()
        if(str01.count("Fun") == 2):
            if(str01.count(",0) == 1)") == 1):
                self.content.edit.setText("#操作失败：此节点不具备点击图功能，请尝试点击此图节点")
                return 0
            
            int01 = str01.find('") == 1):')
            
            self.content.openimage(str01[8:12],str01[15:int01])

            self.grNode.height = 115 + self.content.label.height
            if(self.content.label.width <= 300):
                self.grNode.width = 300
            else:
                self.grNode.width = self.content.label.width
            self.grNode.initContent()
            #self.initSockets(inputs=[], outputs=[1])
            self.time02 = QTimer()
            self.time02.timeout.connect(self.time01)
            self.time02.setInterval(500)
            self.time02.start()
        